#! /usr/bin/env python
#coding=utf-8

import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../"))
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../"))

import loader
from .queriers import ElfModuleInfoQuerierMgr
from utils import ResterHelper
from utils import ResterStringBuilder

from .symbols import ElfSymbolRest
from .deps import DependencyRest

import graphviz

class ElfModuleRest(loader.ElfModule, ResterStringBuilder):
	COMMON_FIELDS = ("id", "object_id", "subsystem", "componentName", "name", "modGroup")
	CATEGORY_COMMON_FIELDS = ("id", "componentName", "name")
	FIELDS_CATEGORIES = {
		"chipsetsdk": CATEGORY_COMMON_FIELDS + ("depth", "deps", "deps_total", "dependedBy", "chipsetsdk_dependedBy", "provided", "used", "chipsetsdk_symbols"),
		"platformsdk": CATEGORY_COMMON_FIELDS + ("depth", "deps", "deps_total", "dependedBy", "platformsdk_dependedBy", "provided", "used", "platformsdk_symbols"),
		"innerapi": CATEGORY_COMMON_FIELDS + ("depth", "deps", "deps_total", "dependedBy", "dependedBy_external", "provided", "used", "external_symbols", "innerapi", "third_party")
	}

	def __init__(self, row, mgr):
		loader.ElfModule.__init__(self, row, mgr)
		self._symbolClass = ElfSymbolRest
		right_tags = []
		for t in ("chipsetsdk", "platformsdk", "chipsetsdk_indirect", "platformsdk_indirect"):
			if t in self and self[t]:
				right_tags.append(t)
		self["right_tags"] = ",".join(right_tags)

	def plotGraph(self, xargs):
		productMgr = xargs["_product_mgr"]
		builder = productMgr.getGraphVizBuilder()
		return builder.buildGraph(self, "modules", xargs)

	def getStr(self, xargs=None, extra_keys=None, extra_vals=None):
		if xargs and "format" in xargs and xargs["format"] == "xml":
			keys = ElfModuleRest.COMMON_FIELDS + ElfModuleInfoQuerierMgr.get_all_keys(xargs)
		elif xargs and "__category" in xargs and xargs["__category"] in ElfModuleRest.FIELDS_CATEGORIES:
			keys = ElfModuleRest.FIELDS_CATEGORIES[xargs["__category"]]
		else:
			keys = ElfModuleRest.COMMON_FIELDS + ElfModuleInfoQuerierMgr.get_all_keys(xargs)
		return ResterStringBuilder.getStr(self, xargs, keys, extra_vals)

	def queryFieldStr(self, cursor, type, xargs):
		return ElfModuleInfoQuerierMgr.query(self, type, cursor, xargs)

class ElfModuleRestMgr(loader.ElfModuleMgr):
	def __init__(self, product):
		super(ElfModuleRestMgr, self).__init__(product.getCursor(), ElfModuleRest, DependencyRest)

	def doRestRequest(self, id, mod, xargs):
		mCmdMap = {
			'fields':self._dbQueryFields,
			'details':self._dbQueryDetails
		}
		return mCmdMap[mod](id, xargs)

	def get_all(self, xargs=None):
		res = super(ElfModuleRestMgr, self).get_all()
		if graphviz.requestingGraphviz(xargs):
				productMgr = xargs["_product_mgr"]
				builder = productMgr.getGraphVizBuilder();
				return builder.plotByModulesType(self, xargs)

		if xargs and "__category" in xargs and xargs["__category"] in ElfModuleRest.FIELDS_CATEGORIES:
			if xargs["__category"] == "innerapi":
				xargs["__greater"] = 1
				xargs["dependedBy_external"] = 0 # Add filter
			else:
				xargs[xargs["__category"]] = 1 # Add filter

		return ResterHelper.filter_contents(res, xargs)

	def _dbQueryFields(self, id, xargs):
		elf = self.find_by_id(int(id))
		return elf.queryFieldStr(self._cursor, xargs["type"], xargs)

	def _dbQueryDetails(self, id, xargs):
		elf = self.find_by_id(int(id))
		return elf.getStr(xargs)

if __name__ == "__main__":
	import products

	product_mgr = products.Products()
	prod = product_mgr.get_all()[0]
	prod.load_db()

	mgr = ElfModuleRestMgr(prod)
	elf = mgr.find_by_id(137)
	print(elf.getStr({"__category":"platformsdk"}))

	#print(mgr.dbGetAllModules())
	#print(mgr._dbGetCallGraphStr({"module_id":136}))
	#print(mgr.dbGetCalledbyGraphStr({"module_id":2}))
	#print(mgr.dbGetSymbols({"callid":136, "calledid":541}))
	#print(mgr.dbGetSymbols({"callid":142, "calledid":204}))
